package com.example.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by dong peng on 2019/11/6.
 */
public class ConsumerDemo {

    public static void main(String[] args) throws InterruptedException {
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "127.0.0.1:9092");
        properties.put("group.id", "group-1");
        properties.put("enable.auto.commit", "false");
        properties.put("auto.commit.interval.ms", "1000");
//        properties.put("auto.offset.reset", "la");
        properties.put("session.timeout.ms", "30000");
        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
        kafkaConsumer.subscribe(Arrays.asList("WordCount"));

        KafkaConsumer<String, String> kafkaConsumer2 = new KafkaConsumer<>(properties);
        kafkaConsumer2.subscribe(Arrays.asList("WordCount"));


        Executor executor =  Executors.newFixedThreadPool(3);
        executor.execute(new Runnable() {
            @Override
            public void run() {
                f(kafkaConsumer);
            }
        });

        executor.execute(new Runnable() {
            @Override
            public void run() {
                f(kafkaConsumer);
            }
        });

    }

    public static  void f(KafkaConsumer kafkaConsumer) {
        while (true) {
            System.out.println(Thread.currentThread().getName());
            ConsumerRecords<String, String> records = kafkaConsumer.poll(3000);
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("offset = %d, value = %s", record.offset(), record.value());
                System.out.println("=====================>");
            }
            kafkaConsumer.commitAsync();
        }
    }
}
